﻿using System;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.Configuration;

namespace Gui.Functies.Home
{
    public partial class Home : UserControl
    {
        private int projectnummer;
        private static string conn = ConfigurationManager.ConnectionStrings["con1"].ConnectionString;
        MySqlConnection grabConnection = new MySqlConnection(conn);

        private int userId;
        private int messageId;
        private int[] messageIDs = new int[100];
        private int[] receiverIDs = new int[100];

        public Home()
        {
            
        }

        public Home(int project, int userID)
        {
            projectnummer = project;
            userId = userID;
            InitializeComponent();
            textBoxMotd.Hide();
            panel1.Hide();
            panelPM.Hide();
            buttonConfirmMotd.Hide();
            HuidigeTaken();
            AgendaToday();
            label2_motd();
            CollectPm();
        }

        // Haalt de message of the day op.
        private void label2_motd()
        {
            try
            {
                MySqlCommand motdGet = new MySqlCommand("SELECT motd FROM motd WHERE projectID=@projectID", grabConnection);
                motdGet.Parameters.Add(new MySqlParameter("projectID", projectnummer));
                grabConnection.Open();
                MySqlDataReader reader = motdGet.ExecuteReader();

                while (reader.Read())
                {
                    label2.Text = reader.GetString(0);
                }

                reader.Dispose();
                motdGet.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                grabConnection.Close();
            }
        }
        //Motd aanpassing confirmen.
        private void buttonConfirmMotd_Click(object sender, EventArgs e)
        {
            textBoxMotd.Hide();
            buttonConfirmMotd.Hide();
            EditMotd();
            labelMotd.Show();
            label2.Show();
        }
        //Motd aanpas tekstbox openen.
        private void buttonCreateMotd_Click(object sender, EventArgs e)
        {
            label2.Hide();
            textBoxMotd.Show();
            buttonConfirmMotd.Show();
        }

        //Methode om de message of the day aan te passen.
        private void EditMotd()
        {
            string newMotd = textBoxMotd.Text;

            if (newMotd != "")
            {
                MySqlCommand editMotd = new MySqlCommand("UPDATE motd SET motd=@motd WHERE projectID=@projectID", grabConnection);
                editMotd.Parameters.Add(new MySqlParameter("motd", newMotd));
                editMotd.Parameters.Add(new MySqlParameter("projectID", projectnummer));

                try
                {
                    grabConnection.Open();
                    editMotd.ExecuteNonQuery();
                }
                catch (MySqlException e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    editMotd.Dispose();
                    grabConnection.Close();
                }

                label2_motd();
            }
            else
            {
                MessageBox.Show("Geen nieuwe Message of the day ingesteld");
            }
        }

        //Haal de meest recente agenda op.
        private void AgendaToday()
        {
            try
            {
                MySqlCommand dayagendaGet = new MySqlCommand("SELECT note FROM agenda WHERE projectID=@projectID", grabConnection);
                dayagendaGet.Parameters.Add(new MySqlParameter("projectID", projectnummer));
                grabConnection.Open();
                MySqlDataReader reader = dayagendaGet.ExecuteReader();
                while (reader.Read())
                {
                    textBox2.Text = reader.GetString(0);

                    if (reader.GetString(0) == "")
                    {
                        textBox2.Text = "No current agenda.";
                    }
                }

                reader.Dispose();
                dayagendaGet.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
                textBox2.Text = "No current agenda.";
            }
            finally
            {
                grabConnection.Close();
            }
        }
        //Haalt de private message inhoud op.
        public void CollectPm()
        {
            try
            {
                MySqlCommand privateMessages = new MySqlCommand("SELECT messageID, subject FROM private_message WHERE userID=@userID", grabConnection);
                privateMessages.Parameters.Add(new MySqlParameter("userID", userId));
                grabConnection.Open();
                MySqlDataReader reader = privateMessages.ExecuteReader();

                string mId;
                int counter = 0;

                while (reader.Read())
                {
                    mId = reader.GetString(0);
                    messageIDs[counter] = Int32.Parse(mId);
                    checkedListBoxBerichten.Items.Add(reader.GetString(1));
                    counter++;
                }

                reader.Dispose();
                privateMessages.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
                checkedListBoxBerichten.Items.Add("No messages");
            }
            finally
            {
                grabConnection.Close();
            }
        }

        //Haalt je private messages op voor je mailbox.
        public void GetMessage(int index)
        {
            try
            {
                messageId = messageIDs[index];
                MySqlCommand privateMessage = new MySqlCommand("SELECT senderID, subject, message FROM private_message WHERE messageID=@messageID", grabConnection);
                privateMessage.Parameters.Add(new MySqlParameter("messageID", messageId));
                grabConnection.Open();
                MySqlDataReader reader = privateMessage.ExecuteReader();
                panel1.Show();
                int senderId = 0;

                while (reader.Read())
                {
                    senderId = Int32.Parse(reader.GetString(0));
                    receiveBox.Text = reader.GetString(1);
                    receiveSubject.Text = reader.GetString(2);
                }

                reader.Dispose();
                privateMessage.Dispose();
                grabConnection.Close();

                //aangezien dit in een aparte connectie opgehaald moet worden moet het buiten de reader gezet worden
                senderLabel.Text = GetSender(senderId);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        //Haalt de persoon op wie het bericht gestuurd heeft
        public string GetSender(int id)
        {
            int userId = id;
            string naam = "No name found";

            //id omzetten naar naam.
            try
            {
                MySqlCommand getReceivers = new MySqlCommand("SELECT Naam, Tussenvoegsel, Achternaam FROM confirmed_users WHERE UserID=@id", grabConnection);
                getReceivers.Parameters.Add(new MySqlParameter("id", userId));
                grabConnection.Open();
                MySqlDataReader reader2 = getReceivers.ExecuteReader();
                while (reader2.Read())
                {
                    naam = reader2.GetString(0) + " " + reader2.GetString(1) + " " + reader2.GetString(2);
                }

                reader2.Dispose();
                getReceivers.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                grabConnection.Close();
            }

            return naam;
        }

        //Haalt de taken op waar mensen op het moment mee bezig zijn.
        public void HuidigeTaken()
        {
            try
            {
                string status = "Bezig";
                MySqlCommand currentTasks = new MySqlCommand("SELECT Taak FROM taken WHERE projectID=@projectID AND Status=@status", grabConnection);
                currentTasks.Parameters.Add(new MySqlParameter("projectID", projectnummer));
                currentTasks.Parameters.Add(new MySqlParameter("status", status));
                grabConnection.Open();
                MySqlDataReader reader = currentTasks.ExecuteReader();

                while (reader.Read())
                {
                    listBoxTaken.Items.Add(reader.GetString(0));
                }

                reader.Dispose();
                currentTasks.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
                textBox2.Text = "No current agenda.";
            }
            finally
            {
                grabConnection.Close();
            }
        }
        // Vind de users waar je messages naar kan sturen.
        public void GetReceivers()
        {
            int counter = 0;
            try
            {
                //userIDs ophalen
                MySqlCommand getReceiverIDs = new MySqlCommand("SELECT UserID FROM project_members WHERE ProjectID=@projectID", grabConnection);
                getReceiverIDs.Parameters.Add(new MySqlParameter("projectID", projectnummer));
                grabConnection.Open();
                MySqlDataReader reader = getReceiverIDs.ExecuteReader();

                string rId;

                while (reader.Read())
                {
                    rId = reader.GetString(0);
                    receiverIDs[counter] = Int32.Parse(rId);
                    counter++;
                }

                reader.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
                checkedListBoxBerichten.Items.Add("No messages");
            }

            //Nu de ids omzetten naar namen.
            try
            {
                MySqlCommand getReceivers = new MySqlCommand("SELECT Naam, Tussenvoegsel, Achternaam FROM confirmed_users WHERE UserID=@receiverid", grabConnection);
                int counter2 = 0;

                for (int i = 0; i <= 10; i++)
                {
                    getReceivers.Parameters.Add(new MySqlParameter("receiverid", receiverIDs[counter2]));
                    MySqlDataReader reader2 = getReceivers.ExecuteReader();
                    while (reader2.Read())
                    {
                        comboBox1.Items.Add(reader2.GetString(0) + " " + reader2.GetString(1) + " " + reader2.GetString(2));
                    }

                    counter2++;
                    getReceivers.Parameters.Remove(new MySqlParameter("receiverid", receiverIDs[counter2]));
                    reader2.Dispose();
                }

                getReceivers.Dispose();
            }
            catch (MySqlException e)
            {
                MessageBox.Show(e.ToString());
                checkedListBoxBerichten.Items.Add("No messages");
            }
            grabConnection.Close();
        }

        //Sends the private message
        public void SendMessage()
        {
            int receiverIndex = comboBox1.SelectedIndex;
            int mUid = receiverIDs[receiverIndex];
            try
            {
                MySqlCommand privateMessage = new MySqlCommand("INSERT INTO private_message (userID, senderID, subject, message)" + "VALUES (@mUID, @mSID, @subject, @message)", grabConnection);
                privateMessage.Parameters.Add(new MySqlParameter("mUID", mUid));
                privateMessage.Parameters.Add(new MySqlParameter("mSID", userId));
                privateMessage.Parameters.Add(new MySqlParameter("subject", textBox3.Text));
                privateMessage.Parameters.Add(new MySqlParameter("message", richTextBox1.Text));
                textBox3.Clear();
                richTextBox1.Clear();
                comboBox1.Items.Clear();
                grabConnection.Open();
                privateMessage.ExecuteNonQuery();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
            finally
            {
                grabConnection.Close();
            }
        }
        //Messages worden hiermee verwijderd.
        public void DeleteMessage()
        {
            int selectedIndex = checkedListBoxBerichten.SelectedIndex;
            int dID = messageIDs[selectedIndex];
            MySqlCommand deleteMsg = new MySqlCommand("DELETE FROM private_message WHERE messageID=@msgdelete", grabConnection);
            deleteMsg.Parameters.Add(new MySqlParameter("msgdelete", dID));

            try
            {
                grabConnection.Open();
                deleteMsg.ExecuteNonQuery();
                grabConnection.Close();
                checkedListBoxBerichten.Items.Clear();
                CollectPm();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        
        //Wordt aangeroepen als je een message aanklikt in de checkedlistbox.
        private void checkedListBoxBerichten_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index = checkedListBoxBerichten.SelectedIndex;
            GetMessage(index);
        }

        //Delete de message die aangeklikt is.
        private void btnDelete_Click(object sender, EventArgs e)
        {
            DeleteMessage();
        }
        
        //Maakt een nieuwe PM aan.
        private void btnCreatePm_Click(object sender, EventArgs e)
        {
            GetReceivers();
            panelPM.Show();
        }

        //Cancelt het maken van een nieuwe pm.
        private void cancelButton_Click(object sender, EventArgs e)
        {
            panelPM.Hide();
        }
        //Stuurt de message
        private void sendButton_Click(object sender, EventArgs e)
        {
            SendMessage();
            panelPM.Hide();
        }
    }
}
